package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import dao.UserDAO;
import service.LoginService;
import service.UserService;
import tools.MyCode;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取登录用到的用户名
		String username=request.getParameter("user");
		String password=request.getParameter("pass");
		//调用业务层，得到运算结果
		LoginService service=new LoginService();
		
		int re=service.check(username, password);
		
		//根据结果，调用表示层
		switch (re) {
		case MyCode.FAIL:
			response.getWriter().write("passwordError");
			break;
		case MyCode.NO:
			response.getWriter().write("unHaveError");
			break;
		case MyCode.SUCCESS:
			loginOK(username,request, response);
			response.getWriter().write("success");
			break;
		default:
			break;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	private void loginOK(String username,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserService userService = new UserService();
		int loginUserId = userService.getIdByName(username);
		
		request.getSession().setAttribute("username", username);
		request.getSession().setAttribute("loginUserId", loginUserId+"");
		
		//登录成功后切换
		//request.getRequestDispatcher("search.goods?likeword=").forward(request, response);
	}
}
